package com.liangtian.mdm.system.log;

import com.liangtian.mdm.base.authentication.JWTUtil;
import com.liangtian.mdm.base.utils.BrowserUtils;
import com.liangtian.mdm.base.utils.IPUtil;
import com.liangtian.mdm.system.log.model.SysLog;
import com.liangtian.mdm.system.log.service.SysLogService;
import com.liangtian.mdm.system.log.service.impl.SysLogServiceImpl;
import com.liangtian.mdm.util.SpringContextUtil;
import com.liangtian.mdm.util.StringUtil;
import org.apache.shiro.SecurityUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class SysLogUtil {

    public static int insertLog(String logContent, String busTable, String operationType, HttpServletRequest request) {
        SysLog log = new SysLog();

        if (!StringUtil.isBlank(logContent)) {
            //--防止超过数据库的最大长度4000,考虑到UTF字符集，这里设置不能超过1000个字符。
            int maxLengthContent = 1000;
            if (logContent.length() > maxLengthContent) {
                logContent = logContent.substring(0, maxLengthContent) + "......";
            }
            log.setOperationContent(logContent);
        }

        log.setBusTable(busTable);
        log.setOperationType(operationType);
        log.setOperationDate(new Date());
        try {
            if (request != null) {
                String token = (String) SecurityUtils.getSubject().getPrincipal();
                String username = JWTUtil.getUsername(token);
                log.setUserName(username);
                log.setIpAddress(IPUtil.getIpAddr(request));
                log.setBrowserType(BrowserUtils.getBrowserName(request));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        SysLogService sysLogService = SpringContextUtil.getBean(SysLogServiceImpl.class);
        return sysLogService.insertLog(log);
    }

}